package com.haibei.activity.topic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.common.net.NetResult;
import com.common.task.BaseTask;
import com.common.task.NetCallBack;
import com.common.uitl.DateTool;
import com.common.uitl.LogUtil;
import com.common.uitl.StringUtils;
import com.common.uitl.Tool;
import com.haibei.App;
import com.haibei.R;
import com.haibei.activity.BaseHaibeiActivity;
import com.haibei.activity.common.CommentActivity;
import com.haibei.activity.user.LoginActivity;
import com.haibei.adapter.ArticleContentAdapter;
import com.haibei.adapter.bean.Comment;
import com.haibei.adapter.bean.ContentItem;
import com.haibei.adapter.bean.Topic;
import com.haibei.adapter.bean.TopicOption;
import com.haibei.adapter.bean.TopicSelected;
import com.haibei.adapter.bean.User;
import com.haibei.net.NetInterface;
import com.haibei.view.PercentView;

/**
 * 话题详情
 * 
 * @author wangzy
 * 
 */
public class TopicDetailActivity extends BaseHaibeiActivity implements OnClickListener {

	private View headerView;
	private View footerView;
	private BaseTask mBaseTask;
	private ListView mListViewTopics;
	private Topic mTopic;
	private Button buttonCollect;
	private final int INT_GO_COMMENT = 100;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mTopic = (Topic) getIntent().getSerializableExtra("topic");
		initView();
	}

	private View createHeaderView() {
		headerView = View.inflate(this, R.layout.header_topic_detail, null);
		return headerView;
	}

	private View createFooterView() {
		footerView = View.inflate(this, R.layout.footerview_topic_vote, null);

		return footerView;
	}

	private void updateHeaderVew(Topic topic) {
		if (null == topic) {
			return;
		}
		TextView txtPeroid = (TextView) headerView.findViewById(R.id.textViewPeroid);
		txtPeroid.setText("第" + topic.getPeriod() + "期");
		TextView textViewTopicTitle = (TextView) headerView.findViewById(R.id.textViewTopicTitle);
		textViewTopicTitle.setText(topic.getTitle());
		TextView textViewTopicAuthfrom = (TextView) headerView.findViewById(R.id.textViewTopicAuthfrom);
		textViewTopicAuthfrom.setText(topic.getAuthor() + " " + topic.getOrigin());
		TextView textViewTopicTime = (TextView) headerView.findViewById(R.id.textViewTopicTime);
		textViewTopicTime.setText(DateTool.getLongTime4Ymdhms(Long.parseLong(topic.getPublishTime())));
		TextView leadingText = (TextView) headerView.findViewById(R.id.textViewLead);
		leadingText.setText("    " + topic.getLead());
	}

	private void updateFooter(final TopicSelected topicSelect, String votes, final Topic topic) {
		if (null == topicSelect) {
			return;
		}

		TextView textVoteTag = (TextView) footerView.findViewById(R.id.textViewOptionsMutipl);
		View lookResult = footerView.findViewById(R.id.textViewLookResult);
		lookResult.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 查看投票结果
			}
		});
		String tagText = topicSelect.getMultipleChoice() == true ? "投票(多选)" : "投票";
		textVoteTag.setText(tagText);
		TextView voteCount = (TextView) footerView.findViewById(R.id.textViewVoteCount);
		voteCount.setText(votes + "人参加投票");
		voteCount.setTag(votes);
		TextView textViewQuestion = (TextView) footerView.findViewById(R.id.textViewQuestion);
		textViewQuestion.setText(topic.getTitle());
		LinearLayout lc = (LinearLayout) footerView.findViewById(R.id.lienarLayoutVoteOptions);
		final List<TopicOption> options = topicSelect.getTopicOptions();
		if (topicSelect.getMultipleChoice()) {
			// 多选
			final HashMap<String, TopicOption> selectOptions = new HashMap<String, TopicOption>();
			View.OnClickListener mClick = new OnClickListener() {
				@Override
				public void onClick(View v) {
					Button btn = (Button) v;
					TopicOption to = (TopicOption) v.getTag();
					if (selectOptions.containsKey(to.getId())) {
						// 已经选择，取消
						btn.setBackgroundResource(R.drawable.btn_vote);
						selectOptions.remove(to.getId());
					} else {
						// 没有选择
						btn.setBackgroundResource(R.drawable.btn_vote_reverse);
						selectOptions.put(to.getId(), to);
					}
				}
			};
			LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			lp.topMargin = (int) getResources().getDimension(R.dimen.margin_micro);
			for (int i = 0, isize = options.size(); i < isize; i++) {
				TopicOption option = options.get(i);
				Button btn = (Button) View.inflate(this, R.layout.button_vote, null);
				btn.setBackgroundResource(R.drawable.btn_vote);
				btn.setTag(option);
				btn.setText(option.getContent());
				btn.setOnClickListener(mClick);
				lc.addView(btn, lp);
			}
			Button btnVote = new Button(this);
			btnVote.setText("确定");
			// btnVote.setTextSize(getResources().getDimension(R.dimen.label_text_size_third));
			btnVote.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					LogUtil.i(App.tag, "多选投票...");
					User u = App.getApp().getUser();
					if (null == u) {
						Tool.startOtherActivity(TopicDetailActivity.this, LoginActivity.class);
					} else {
						HashMap<String, String> hmap = new HashMap<String, String>();
						hmap.put("uid", u.getUid());
						hmap.put("topicId", mTopic.getId());
						StringBuffer sb=new StringBuffer();
						for (Entry<String, TopicOption> entry : selectOptions.entrySet()) {
							sb.append(entry.getValue().getId()+",");
						}
						String str=sb.toString();
						if(!StringUtils.isEmpty(str)){
							str=str.substring(0, str.length()-2);
							hmap.put("topicOptionIds", str);
							hmap.put("topicSelectedId", topicSelect.getId());
							getBatchVoteTask(topicSelect, selectOptions).execute(hmap);
						}
					}
				}
			});

			btnVote.setBackgroundResource(R.drawable.btn_reply);
			lc.addView(btnVote, lp);
		} else {
			// 单选
			View.OnClickListener click = new OnClickListener() {
				@Override
				public void onClick(View v) {
					User u = App.getApp().getUser();
					if (null == u) {
						Tool.startOtherActivity(TopicDetailActivity.this, LoginActivity.class);
					} else {
						TopicOption option = (TopicOption) v.getTag();
						HashMap<String, String> hmap = new HashMap<String, String>();
						hmap.put("uid", u.getUid());
						hmap.put("topicId", mTopic.getId());
						hmap.put("topicSelectedId", String.valueOf(topicSelect.getId()));
						hmap.put("topicOptionId", option.getId());
						getVoteTask(topicSelect, option).execute(hmap);
					}
				}
			};
			LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			lp.topMargin = (int) getResources().getDimension(R.dimen.margin_micro);
			for (int i = 0, isize = options.size(); i < isize; i++) {
				TopicOption option = options.get(i);
				Button btn = (Button) View.inflate(this, R.layout.button_vote, null);
				btn.setBackgroundResource(R.drawable.btn_vote);
				btn.setTag(option);
				btn.setText(option.getContent());
				btn.setOnClickListener(click);
				lc.addView(btn, lp);
			}
		}
	}

	@Override
	public void initView() {
		setContentView(R.layout.activity_topic_detail);
		mListViewTopics = findListViewById(R.id.listViewTopics);
		mListViewTopics.addHeaderView(createHeaderView());
		mListViewTopics.addFooterView(createFooterView());
		updateHeaderVew(mTopic);
		findViewById(R.id.linearLayoutBottomReply).setOnClickListener(this);
		findButtonById(R.id.buttonBack).setOnClickListener(this);
		findButtonById(R.id.buttonCollect).setOnClickListener(this);
		// if (null == mTopic) {
		requestTopicDetail();
		// }
	}

	private void buildAdater(Topic topic, String commetCount) {
		updateHeaderVew(topic);
		// LogUtil.i(App.tag, "tpic:" + topic.getContent());
		ArrayList<ContentItem> list = topic.getCotentList();
		ArticleContentAdapter aca = new ArticleContentAdapter(this, list);
		mListViewTopics.setAdapter(aca);
	}

	private void requestTopicDetail() {
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("topicId", mTopic.getId());
		getDetailBaseTask().execute(params);
	}

	private void comment(String topicId, String content) {
		// uid, topicId, commentContent);
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("uid", App.getApp().getUser().getUid());
		params.put("topicId", topicId);
		params.put("commentContent", content);
		getCommentBaseTask().execute(params);
	}

	private BaseTask getCommentBaseTask() {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}

		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onPreCall() {
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						Comment coment = (Comment) result.getData()[0];
						Tool.ToastShow(TopicDetailActivity.this, "评论成功！");
						gotoComments();
					} else {
						Tool.ToastShow(TopicDetailActivity.this, result.getMessage());
					}
				} else {
					Tool.ToastShow(TopicDetailActivity.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.addParComment4Topic(TopicDetailActivity.this, paramMap);
				} catch (Exception e) {
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	private void gotoComments() {
		Intent i = new Intent();
		i.putExtra("topic", mTopic);
		i.setClass(TopicDetailActivity.this, TopicommentsActivity.class);
		startActivity(i);
		// Tool.startActivity(TopicDetailActivity.this,
		// TopicommentsActivity.class);
	}

	/**
	 * 获取话题详情Task
	 * 
	 * @return
	 */
	private BaseTask getDetailBaseTask() {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onPreCall() {
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						mTopic = (Topic) result.getData()[0];
						String voteCount = (String) result.getData()[1];
						Object topicOptions = result.getData()[2];
						buildAdater(mTopic, voteCount);
						if (null != topicOptions) {
							LogUtil.i(App.tag, "投票问题已经加载。。");
							updateFooter((TopicSelected) topicOptions, voteCount, mTopic);
						}

					} else {
						Tool.ToastShow(TopicDetailActivity.this, result.getMessage());
					}
				} else {
					Tool.ToastShow(TopicDetailActivity.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.detailTopic(TopicDetailActivity.this, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	@Override
	public void onClick(View v) {
		int vid = v.getId();
		switch (vid) {
		case R.id.linearLayoutBottomReply: {
			User u = App.getApp().getUser();
			if (null != u) {
				Intent i = new Intent();
				i.setClass(TopicDetailActivity.this, CommentActivity.class);
				startActivityForResult(i, INT_GO_COMMENT);
			} else {
				Tool.startActivity(TopicDetailActivity.this, LoginActivity.class);
			}
		}
			break;
		case R.id.buttonBack: {
			finish();
		}
			break;
		case R.id.buttonCollect: {
			if (App.isLogin()) {
				collectTopic(mTopic);
			} else {
				Tool.startActivity(TopicDetailActivity.this, LoginActivity.class);
			}
		}
			break;
		default:
			break;
		}
	}

	// 收藏话题
	private void collectTopic(Topic topic) {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onPreCall() {
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						Tool.ToastShow(TopicDetailActivity.this, "收藏成功");
					} else {
						Tool.ToastShow(TopicDetailActivity.this, result.getMessage());
					}
				} else {
					Tool.ToastShow(TopicDetailActivity.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netRsult = null;
				try {
					netRsult = NetInterface.collectTopic(TopicDetailActivity.this, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netRsult;
			}
		});
		HashMap<String, String> hmap = new HashMap<String, String>();
		// uid, topicId);
		hmap.put("topicId", mTopic.getId());
		hmap.put("uid", App.getApp().getUser().getUid());
		mBaseTask.execute(hmap);
	}

	private void updateVotePeopleCount() {
		TextView text = ((TextView) footerView.findViewById(R.id.textViewVoteCount));
		int count = Integer.parseInt((String) text.getTag()) + 1;
		text.setTag(String.valueOf(count));
		text.setText((count) + "人参加投票");
	}

	private void voteEnd(NetResult netResult, TopicSelected topicSelect, TopicOption to) {
		if (null != netResult) {
			if (netResult.isSuccess()) {
				Tool.ToastShow(TopicDetailActivity.this, "投票成功！");
				updateVotePeopleCount();
				updateResult(topicSelect, to);
			} else {
				Tool.ToastShow(TopicDetailActivity.this, netResult.getMessage());
			}
		} else {
			Tool.ToastShow(TopicDetailActivity.this, "网络错误！");
		}
	}

	private void voteBacthEnd(NetResult netResult, TopicSelected topicSelect,HashMap<String, TopicOption> selects) {
		if (null != netResult) {
			if (netResult.isSuccess()) {
				Tool.ToastShow(TopicDetailActivity.this, "投票成功！");
				updateVotePeopleCount();
				updateResult(topicSelect, selects);
			} else {
				Tool.ToastShow(TopicDetailActivity.this, netResult.getMessage());
			}
		} else {
			Tool.ToastShow(TopicDetailActivity.this, "网络错误！");
		}
	}
	/**
	 * 投票结果
	 * 
	 * @param topSelect
	 * @param selectedTo
	 */
	private void updateResult(TopicSelected topSelect, TopicOption selectedTo) {
		footerView.findViewById(R.id.lienarLayoutVoteOptions).setVisibility(View.INVISIBLE);
		LinearLayout lienarLayoutVoteOptions = (LinearLayout) footerView.findViewById(R.id.lienarLayoutVoteResult);
		List<TopicOption> oplist = topSelect.getTopicOptions();
		float voteCount = 0;
		for (int i = 0, isize = oplist.size(); i < isize; i++) {
			voteCount += oplist.get(i).getVoteCount();
		}
		for (int i = 0, isize = oplist.size(); i < isize; i++) {
			TopicOption to = oplist.get(i);
			float percent = to.getVoteCount() / voteCount;
			View voteItem = View.inflate(TopicDetailActivity.this, R.layout.item_vote_percent, null);
			TextView txtView = (TextView) voteItem.findViewById(R.id.txtViewOptionText);
			View viewSpace = voteItem.findViewById(R.id.viewSpace);

			txtView.setText(to.getContent());

			LinearLayout.LayoutParams lp1 = new LayoutParams(0, 20);
			PercentView percentView = (PercentView) voteItem.findViewById(R.id.percentView);
			lp1.weight = percent;
			percentView.setLayoutParams(lp1);
			percentView.setColor(createColor(i));

			LinearLayout.LayoutParams lp2 = new LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
			lp2.weight = (1 - percent);
			TextView percentText = (TextView) voteItem.findViewById(R.id.textViewPercent);
			percentText.setText((int) (percent * 100) + "%");
			viewSpace.setLayoutParams(lp2);
			lienarLayoutVoteOptions.addView(voteItem);
		}
	}

	private void updateResult(TopicSelected topSelect, HashMap<String, TopicOption> selects) {
		footerView.findViewById(R.id.lienarLayoutVoteOptions).setVisibility(View.INVISIBLE);
		LinearLayout lienarLayoutVoteOptions = (LinearLayout) footerView.findViewById(R.id.lienarLayoutVoteResult);
		List<TopicOption> oplist = topSelect.getTopicOptions();
		float voteCount = 0;
		for (int i = 0, isize = oplist.size(); i < isize; i++) {
			voteCount += oplist.get(i).getVoteCount();
		}
		for (int i = 0, isize = oplist.size(); i < isize; i++) {
			TopicOption to = oplist.get(i);
			float percent = to.getVoteCount() / voteCount;
			View voteItem = View.inflate(TopicDetailActivity.this, R.layout.item_vote_percent, null);
			TextView txtView = (TextView) voteItem.findViewById(R.id.txtViewOptionText);
			View viewSpace = voteItem.findViewById(R.id.viewSpace);

			txtView.setText(to.getContent());

			LinearLayout.LayoutParams lp1 = new LayoutParams(0, 20);
			PercentView percentView = (PercentView) voteItem.findViewById(R.id.percentView);
			lp1.weight = percent;
			percentView.setLayoutParams(lp1);
			percentView.setColor(createColor(i));

			LinearLayout.LayoutParams lp2 = new LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
			lp2.weight = (1 - percent);
			TextView percentText = (TextView) voteItem.findViewById(R.id.textViewPercent);
			percentText.setText((int) (percent * 100) + "%");
			viewSpace.setLayoutParams(lp2);
			lienarLayoutVoteOptions.addView(voteItem);
		}
	}
	private int createColor(int i) {
		int color[] = { 0xff8dda1a, 0xff4abdcc, 0xffff9999, 0xff13da1a, 0xff4ccdcc };
		return color[i];
	}

	private BaseTask getVoteTask(final TopicSelected topicSelect, final TopicOption to) {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {

			@Override
			public void onPreCall() {
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				to.setVoteCount((to.getVoteCount() + 1));
				voteEnd(result, topicSelect, to);
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.voteTopic(TopicDetailActivity.this, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	private BaseTask getBatchVoteTask(final TopicSelected topicSelect,  final HashMap<String, TopicOption> optionsMap) {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {

			@Override
			public void onPreCall() {
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				for(Entry<String, TopicOption> entrys:optionsMap.entrySet()){
					TopicOption	to=entrys.getValue();
					to.setVoteCount((to.getVoteCount() + 1));
				}
				voteBacthEnd(result, topicSelect, optionsMap);
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.voteBatchTopic(TopicDetailActivity.this, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (INT_GO_COMMENT == requestCode) {
			if (RESULT_OK == resultCode) {
				// ServiceResult<Comment> result =
				// commentService.addParTopicComment(uid, topicId,
				// commentContent);
				String content = data.getStringExtra("data");
				comment(mTopic.getId(), content);
			}
		}
	}
}
